package com.qkl.xiatang.app.service.redis;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class RedisService {

    @Value("${spring.redis.keyPrefix}")
    private String keyPrefix;

    //@Autowired
    //private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private StringRedisTemplate redisStringTemplate;

    /**
    public void setValue(String key,Object value){
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        opsForValue.set(key, value);
    }
     **/

    public boolean lock(String key, String value, long timeout) {
        String redisKey = this.getRedisKey(key);
        if (redisStringTemplate.opsForValue().setIfAbsent(redisKey, value)) {
            redisStringTemplate.expire(redisKey, timeout, TimeUnit.MILLISECONDS);
            return true;
        }
        return false;
    }

    public boolean releaseLock(String key, String value) {
        String redisKey = this.getRedisKey(key);
        String currentValue = redisStringTemplate.opsForValue().get(redisKey);
        if (currentValue != null && currentValue.equals(value)) {
            redisStringTemplate.delete(redisKey);
            return true;
        }
        return false;
    }

    private String getRedisKey(String key){
        String redisKey = StringUtils.trimToEmpty(keyPrefix) + "_" + key;
        log.info("======getRedisKey.redisKey={}",redisKey);
        return redisKey;
    }


}
